package org.oc.qaq.controller;

import org.oc.qaq.entity.elasticsearch.DocumentSegment;
import org.oc.qaq.result.Result;
import org.oc.qaq.service.Impl.DocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/api/v1/search")
public class SearchController {

    @Autowired
    DocumentService documentService;

    @GetMapping
    public Result<?> searchArticle(@RequestParam String keyword) {
        SearchHits<DocumentSegment> hits = documentService.search(keyword);
        return Result.success(hits.getSearchHits().stream().map(hit -> {
            DocumentSegment doc = hit.getContent();

            // 高亮字段覆盖
            List<String> highlightContent = hit.getHighlightFields().get("content");
            if (highlightContent != null && !highlightContent.isEmpty()) {
                doc.setContent(highlightContent.get(0));
            }

            return doc;
        }).toList());
    }
}
